package com.hundsun.yr.universal.p2p.ui.activity;

import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.LoanParam;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseMineWebActivity;
import com.hundsun.yr.universal.p2p.ui.view.ProgressDailog;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.utils.KeyBoardListener;
import com.hundsun.yr.universal.p2p.utils.Logs;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 授信支付界面
 */
public class WebFDDProtocolActivity extends BaseMineWebActivity implements OnClickListener{
    public final static String PARAMS = "PARAMS";
    public final static String APPLYID = "APPLYID";
    private String applyId = "";
    private LoanParam params;
    private HSSharedPreferences sharedPreferences = null;
    private boolean isFirst = true;
    /** 加载进度条 **/
    protected ProgressDailog progressDailog = null;
    /**
     * 状态判断0表示还未提交1表示签章成功，-1表示签章失败
     */
    private int status = 0;
    private String zwgt_data;

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected View getLoadingTargetView() {

        return mBrowserLayout;
    }


    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        mBrowserLayout.refresh();
        toggleHide();
    }

    @Override
    protected void getBundleExtras(Bundle bundle) {
        applyId = bundle.getString(APPLYID);
        params = (LoanParam) bundle.getSerializable(PARAMS);
        super.getBundleExtras(bundle);
    }

    @Override
    protected void onNetworkDisConnected() {

        toggleNetworkError(true, new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (NetUtils.isNetworkConnected(getBaseContext())) {
                    showToast("请检查网络...");
                } else {
                    mBrowserLayout.refresh();
                    toggleHide();
                }
            }
        });

    }


    @Override
    protected void initViewsAndEvents() {
        super.initViewsAndEvents();
        KeyBoardListener.getInstance(this).init();
        progressDailog = new ProgressDailog(this, R.style.progress_dialog);
        sharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_userLoginedInfo);
        toolbar_title.setText(mWebTitle);
        mContext = this;
        mBrowserLayout.mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains(getString(R.string.login_successful2))){
                    //判断是否设置过交易密码
                    if (TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_PAYPWD), "YES")){
                        //跳转至交易密码设置界面
                        readyGoThenKill(UpdatePayPwdActivity.class);
                    } else {
                        setPwd();
                    }
                    return true;
                } if (isFirst && url.contains(getString(R.string.root_h5_url_test))) {
                    status = 1;
                    int index = url.indexOf("uuid");
                    String uuid = url.substring(index);
                    int i = uuid.indexOf("=");
                    uuid = uuid.substring(i + 1);
                    confirmBorrowApply(uuid);
                    isFirst = false;
                    progressDailog.showProgress();
                    return true;
                } else {
                    mBrowserLayout.mWebView.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {

                super.onPageCommitVisible(view, url);
            }

        });
    }

    protected void setPwd() {
        progressDailog.showProgress();
        StringRequestInteractorImpl requestinteractor = new StringRequestInteractorImpl(new BaseMultiLoadedListener<String>() {

            @Override
            public void onSuccess(String task_name, int event_tag, String data) {
                progressDailog.dismiss();
                AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
                UpdatePayPwdBeen mUpdatePayPwdBeen = null;
                try {
                    String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                    String[] split = decode.split("\\n");
                    mUpdatePayPwdBeen = (UpdatePayPwdBeen) GsonTool.getInstanceByJson(UpdatePayPwdBeen.class,split[1]);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                switch (adSlideBeen.code) {
                    case Constants.REQUESTCODE_000000:
                        if (mUpdatePayPwdBeen == null){
                            return;
                        }

                        //现在做另外一种操作
                        String postData = null;
                        try {
                            postData = "accountId=" + URLEncoder.encode(mUpdatePayPwdBeen.data.accountId.toString(), "utf-8") + "&acqRes=" + URLEncoder.encode(mUpdatePayPwdBeen.data.acqRes.toString(),"utf-8") +
                                    "&bankCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.bankCode.toString(),"utf-8") + "&channel=" + URLEncoder.encode(mUpdatePayPwdBeen.data.channel.toString(), "utf-8") +
                                    "&idNo=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idNo.toString(),"utf-8") + "&idType=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idType.toString(),"utf-8") + "&instCode=" +
                                    URLEncoder.encode(mUpdatePayPwdBeen.data.instCode.toString(),"utf-8") + "&lastSrvAuthCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.lastSrvAuthCode == null ? "": mUpdatePayPwdBeen.data.lastSrvAuthCode.toString(),"utf-8") +
                                    "&mobile=" + URLEncoder.encode(mUpdatePayPwdBeen.data.mobile.toString(),"utf-8") + "&name=" + URLEncoder.encode(mUpdatePayPwdBeen.data.name.toString(),"utf-8") + "&notifyUrl=" +
                                    URLEncoder.encode(mUpdatePayPwdBeen.data.notifyUrl.toString(),"utf-8") +"&retUrl=" + URLEncoder.encode(mUpdatePayPwdBeen.data.retUrl.toString(),"utf-8") + "&seqNo=" +
                                    URLEncoder.encode(mUpdatePayPwdBeen.data.seqNo.toString(),"utf-8") + "&sign=" + URLEncoder.encode(mUpdatePayPwdBeen.data.sign.toString(),"utf-8") + "&smsCode=" +
                                    URLEncoder.encode(mUpdatePayPwdBeen.data.smsCode == null ? "":mUpdatePayPwdBeen.data.smsCode.toString(),"utf-8") + "&txCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txCode.toString(),"utf-8") +
                                    "&txDate=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txDate.toString(),"utf-8") + "&txTime=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txTime.toString(),"utf-8") + "&version=" +
                                    URLEncoder.encode(mUpdatePayPwdBeen.data.version.toString(),"utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        Bundle bundle = new Bundle();
                        bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.set_paywd));
                        bundle.putString(BaseWebActivity.BUNDLE_KEY_URL,mUpdatePayPwdBeen.url );
                        bundle.putString(BaseWebActivity.BUNDLE_KEY_PARAMS,postData);
                        bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.POSTDATA.getIntValue());
                        bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                        readyGoThenKill(WebSetPasswordActivity.class, bundle);
                        if (BaseAppManager.getInstance().getActivity(MineSettingActivity.class) != null){
                            BaseAppManager.getInstance().getActivity(MineSettingActivity.class).finish();
                        }
                        break;

                    case Constants.REQUESTCODE_100500:
                        break;
                    case Constants.REQUESTCODE_100020:
                        break;
                    case Constants.REQUESTCODE_100010:
                        break;
                    default:
                        showToast(adSlideBeen.msg);
                        break;
                }
            }

            @Override
            public void onException(String task_name, String msg) {
                progressDailog.dismiss();
            }
        });

//        zwgt_data = BaseRequestTool2.getFormatedDateString();
//        JSONObject map = new JSONObject();
//        try {
//            map.put("vcode", "");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
//        requestinteractor.getRequestData(TaskConstants.TASK_SETBANKPWD, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, Constants.EVENT_DATA,
//                jsonParams,BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, sharedPreferences
//                        .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data));
        readyGo(MineSettingActivity.class);
    }

    /**
     *
     * @param uuid
     */
    protected void confirmBorrowApply(String uuid) {
        StringRequestInteractorImpl requestinteractor = new StringRequestInteractorImpl(new BaseMultiLoadedListener<String>() {

            @Override
            public void onSuccess(String task_name, int event_tag, String data) {
                AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
                switch (adSlideBeen.code) {
                    case Constants.REQUESTCODE_000000:
                        //访问网络成功
                        try {
                            String decode = AndroidDes3Util.decode(adSlideBeen.data, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                            String[] split = decode.split("\\n");
                            Bundle bundle = new Bundle();
                            bundle.putString(BaseWebActivity.BUNDLE_KEY_URL,split[1]);
                            bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, mContext.getString(R.string.sign_fdd));
                            bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                            readyGo(WebFDDActivity.class, bundle);
                            finish();
//                            BaseAppManager.getInstance().getActivity(IWantLoanActivity.class).finish();
                            progressDailog.dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;

                    case Constants.REQUESTCODE_100600:
                        showToast(mContext.getString(R.string.login_overdue));
                        CommTool.goToLogin(mContext);
                        progressDailog.dismiss();
                        break;
                    default:
                        Logs.e(adSlideBeen.code +  "?   " + adSlideBeen.msg);
                        showToast(adSlideBeen.msg);
                        progressDailog.dismiss();
                        finish();
                        break;
                }
            }

            @Override
            public void onException(String task_name, String msg) {
                progressDailog.dismiss();
            }
        });

        zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
            map.put("uuid", uuid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);

        requestinteractor.getRequestData(TaskConstants.TASK_FDDSIGN, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_loan_test) +
                TaskConstants.TASK_FDDSIGN, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext,TaskConstants.TASK_POST, mContext.getString(R.string.api_loan_test)
                + TaskConstants.TASK_FDDSIGN,sharedPreferences.getShareProf(UserInfo.USER_NO),sharedPreferences.getShareProf(UserInfo.TOKENID),zwgt_data));
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void onClick(View v) {

    }
}
